package com.getpebble.android.framework.protocol.inbound;

import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.PebbleColor;
import com.getpebble.android.framework.protocol.EndpointId;
import java.nio.ByteBuffer;

public class PblInboundRegistryMessage extends PblInboundMessage {
    public static final String TAG = PblInboundRegistryMessage.class.getSimpleName();
    private ByteBuffer mBuffer;
    private EndpointId mEndpointId;
    private PebbleColor mPebbleColor = null;
    private RegistryResponse mResponse;

    public enum RegistryResponse {
        READ_SUCCESS(1),
        WRITE_SUCCESS(3),
        REMOVE_SUCCESS(5),
        ERROR(-1);
        
        private final int id;

        private RegistryResponse(int id) {
            this.id = id;
        }

        public int getId() {
            return this.id;
        }

        public static RegistryResponse fromId(int id) {
            for (RegistryResponse registryResponse : values()) {
                if (registryResponse.getId() == id) {
                    return registryResponse;
                }
            }
            return ERROR;
        }
    }

    public PblInboundRegistryMessage(ProtocolMessage message) {
        super(message);
        this.mEndpointId = EndpointId.fromCode(message.getEndpointId());
        this.mBuffer = message.getDataBuffer();
        this.mResponse = RegistryResponse.fromId(this.mBuffer.get() & 255);
        if (this.mResponse == RegistryResponse.ERROR) {
            Trace.warning(TAG, "PblInboundRegistryMessage error");
        }
    }

    protected void checkEndpointId(ProtocolMessage message) {
        EndpointId endpointId = EndpointId.fromCode(message.getEndpointId());
        if (!endpointId.equals(EndpointId.FCT_REG) && !endpointId.equals(EndpointId.SYS_REG)) {
            throw new IllegalArgumentException("ProtocolMessage's endpointId must be " + EndpointId.FCT_REG.name() + " or " + EndpointId.SYS_REG.name());
        }
    }

    public PebbleColor asColor() {
        if (this.mPebbleColor == null) {
            this.mPebbleColor = PebbleColor.COLOR_UNKNOWN;
            if (this.mResponse.equals(RegistryResponse.READ_SUCCESS)) {
                int valueLength = this.mBuffer.get() & 255;
                Trace.info(TAG, "RegistryColorResponse read OK valueLength = " + valueLength);
                if (valueLength == 4) {
                    int color = this.mBuffer.getInt();
                    Trace.info(TAG, "PblInboundRegistryMessage: " + color);
                    this.mPebbleColor = PebbleColor.fromInt(color);
                }
            }
        }
        return this.mPebbleColor;
    }

    public EndpointId getId() {
        return this.mEndpointId;
    }

    protected int getMinSize() {
        return 1;
    }
}
